package com.achang.achangmall.search.service.impl;

import com.achang.achangmall.search.conf.ElasticsearchConfig;
import com.achang.achangmall.search.constant.ESConstant;
import com.achang.achangmall.search.service.MallSearchService;
import com.achang.achangmall.search.vo.SearchParam;
import com.achang.achangmall.search.vo.SearchResult;
import com.achang.common.to.es.SkuEsModel;
import com.alibaba.fastjson.JSON;
import org.apache.lucene.search.join.ScoreMode;
import org.apache.lucene.util.QueryBuilder;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.swing.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/******
 @author 阿昌
 @create 2021-10-08 21:55
 *******
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Resource
    private RestHighLevelClient client;

    @Override
    public SearchResult search(SearchParam param) {
        SearchResult result = null;
        SearchRequest request = buildSearchRequest(param);

        try {
            SearchResponse response = client.search(request, ElasticsearchConfig.COMMON_OPTIONS);

            result = buildSearchResult(response,param);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return result;
    }

    //构建结果数据
    private SearchResult buildSearchResult(SearchResponse response,SearchParam param) {
        SearchResult result = new SearchResult();
        SearchHits hits = response.getHits();
        SearchHit[] hitsHits = hits.getHits();//命中数据
        //查询到的所有商品
        List<SkuEsModel> products = new ArrayList<>(hitsHits.length);
        if (!StringUtils.isEmpty(hitsHits)&&hitsHits.length>0){
            for (SearchHit hitsHit : hitsHits) {
                String sourceAsString = hitsHit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                HighlightField skuTitle = hitsHit.getHighlightFields().get("skuTitle");
                if (!StringUtils.isEmpty(param.getKeyword())){
                    skuEsModel.setSkuTitle(skuTitle.getFragments()[0].toString());//设置高亮text
                }
                products.add(skuEsModel);
            }
        }
        result.setProducts(products);


        //商品所涉及到的所有属性信息
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>(buckets.size());
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");

            catalogVo.setCatalogName(catalog_name_agg.getBuckets().get(0).getKeyAsString());
            catalogVo.setCatalogId((int) Long.parseLong(bucket.getKeyAsString()));
            catalogVos.add(catalogVo);
        }
        result.setCatalogVos(catalogVos);

        //商品所涉及到所有的品牌信息
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> brandAggBuckets = brand_agg.getBuckets();
        List<SearchResult.BrandVo> brandVos = new ArrayList<>(brandAggBuckets.size());
        for (Terms.Bucket brandAggBucket : brandAggBuckets) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            ParsedStringTerms brand_img_agg = brandAggBucket.getAggregations().get("brand_img_agg");
            ParsedStringTerms brand_name_agg = brandAggBucket.getAggregations().get("brand_name_agg");

            brandVo.setBrandName(brand_name_agg.getBuckets().get(0).getKeyAsString());
            brandVo.setBrandImg(brand_img_agg.getBuckets().get(0).getKeyAsString());
            brandVo.setBrandId((int) brandAggBucket.getKeyAsNumber().longValue());
            brandVos.add(brandVo);
        }
        result.setBrandVos(brandVos);

        //当前商品所及到所有的属性信息
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> attrIdAggBuckets = attr_id_agg.getBuckets();
        List<SearchResult.AttrVo> attrVos = new ArrayList<>(attrIdAggBuckets.size());
        for (Terms.Bucket attrIdAggBucket : attrIdAggBuckets) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            int id = attrIdAggBucket.getKeyAsNumber().intValue();
            ParsedStringTerms attr_name_agg = attrIdAggBucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            ParsedStringTerms attr_value_agg = attrIdAggBucket.getAggregations().get("attr_value_agg");
            List<? extends Terms.Bucket> value_aggBuckets = attr_value_agg.getBuckets();

            ArrayList<String> attrValueList = new ArrayList<>();
            for (Terms.Bucket value_aggBucket : value_aggBuckets) {
                String attrValue = value_aggBucket.getKeyAsString();
                attrValueList.add(attrValue);
            }

            attrVo.setAttrName(attrName);
            attrVo.setAttrId(id);
            attrVo.setAttrValues(attrValueList);
            attrVos.add(attrVo);
        }
        result.setAttrVos(attrVos);


        //总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //总页码
        int totalPage = (int) ((total%ESConstant.PRODUCT_PAGESIZE)==0?(int)((total/ESConstant.PRODUCT_PAGESIZE)):total/(int)(ESConstant.PRODUCT_PAGESIZE+1));
        result.setTotalPage(totalPage);
        //页码
        result.setPageNum(param.getPageNum());

        ArrayList<Integer> integers = new ArrayList<>();
        for (int i = 1 ; i<= totalPage;i++){
            integers.add(i);
        }
        result.setPageNavs(integers);


        return result;
    }

    //准备检索请求
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();//构建dsl语句

        //查询条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        String keyword = param.getKeyword();
        if (!StringUtils.isEmpty(keyword)){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",keyword));
        }
        Long catalog3Id = param.getCatalog3Id();
        if (!StringUtils.isEmpty(catalog3Id)){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",catalog3Id));
        }
        List<Long> brandId = param.getBrandId();
        if (!StringUtils.isEmpty(brandId) && brandId.size()>0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",brandId));
        }
        Integer hasStock = param.getHasStock();
        if (!StringUtils.isEmpty(hasStock)){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",hasStock==1));
        }
        List<String> attrs = param.getAttrs();
        if (!StringUtils.isEmpty(attrs)&&attrs.size()>0){
            for (String attr : attrs) {
                BoolQueryBuilder nestedBootQuery = QueryBuilders.boolQuery();
                String[] attrStr = attr.split("_");
                String attrId = attrStr[0];
                String[] attrValues = attrStr[1].split(":");
                nestedBootQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedBootQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBootQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }
        }
        String skuPrice = param.getSkuPrice();
        if (!StringUtils.isEmpty(skuPrice)){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] strArr = skuPrice.split("_");
            if (strArr.length==2){
                rangeQuery.gte(strArr[0]).lte(strArr[1]);
            }else if (strArr.length==1){
                if (skuPrice.startsWith("_")){
                    rangeQuery.lte(strArr[1]);
                }
                if (skuPrice.endsWith("_")){
                    rangeQuery.gte(strArr[0]);
                }
            }
            boolQueryBuilder.filter(rangeQuery);
        }
        searchSourceBuilder.query(boolQueryBuilder);

        //排序
        String sort = param.getSort();
        if (!StringUtils.isEmpty(sort)) {
            String[] split = sort.split("_");
            SortOrder order= null;
            if ("asc".equalsIgnoreCase(split[1])){
                order= SortOrder.ASC;
            }else if ("desc".equalsIgnoreCase(split[1])){
                order = SortOrder.DESC;
            }
            searchSourceBuilder.sort(split[0], order);
        }

        //分页
        searchSourceBuilder.from((param.getPageNum()-1)*ESConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(ESConstant.PRODUCT_PAGESIZE);

        //高亮
        if (!StringUtils.isEmpty(keyword)){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        //聚合分析
        //- 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(10);
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").size(1).field("brandName"));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").size(1).field("brandImg"));
        searchSourceBuilder.aggregation(brand_agg);
        //- 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalog_agg);
        //- 属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").size(10).field("attrs.attrId");
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").size(10).field("attrs.attrValue"));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").size(50).field("attrs.attrName"));
        attr_agg.subAggregation(attr_id_agg);
        searchSourceBuilder.aggregation(attr_agg);

        SearchRequest request = new SearchRequest(new String[]{ESConstant.PRODUCT_INDEX},searchSourceBuilder);
        return request;
    }
}
